package com.example.erhuo.activity;

import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.example.erhuo.R;
import com.example.erhuo.api.NetAPI;

import org.apache.http.conn.ConnectTimeoutException;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.net.SocketTimeoutException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.RequestBody;
import okhttp3.Response;

public class LoginActivity extends AppCompatActivity {
    private static final String TAG = "LoginActivity";
    private EditText editTextUsername;
    private EditText editPassword;
    private Button buttonLogin;
    private Button buttonRegister;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
            actionBar.setCustomView(R.layout.title_layout);
            TextView textView = (TextView) actionBar.getCustomView().findViewById(R.id.display_title);
            textView.setText("登录");
            actionBar.setHomeButtonEnabled(true);
            actionBar.setDisplayHomeAsUpEnabled(true);
            actionBar.setDisplayShowCustomEnabled(true);
        }
        setContentView(R.layout.activity_login);
        buttonLogin = findViewById(R.id.information_button_commit);
        buttonRegister = findViewById(R.id.login_btn_register);
        editTextUsername = findViewById(R.id.login_edit_account);
        editPassword = findViewById(R.id.login_edit_pwd);


        buttonRegister.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(LoginActivity.this, RegisterActivity.class);
                startActivity(intent);
            }
        });

        buttonLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //todo
                String username = editTextUsername.getText().toString();
                String password = editPassword.getText().toString();
                if (username.equals("") || password.equals("")) {
                    AlertDialog.Builder builder = new AlertDialog.Builder(LoginActivity.this);
                    builder.setTitle("不能为空!");
                    builder.setMessage("请填写全部注册信息");
                    builder.setPositiveButton("好的", null);
                    builder.show();
                    return;
                }
                RequestBody body = new FormBody.Builder()
                        .add("username", username)
                        .add("password", password)
                        .build();
                Callback callback = new Callback() {
                    @Override
                    public void onFailure(@NonNull Call call, @NonNull IOException e) {
                        if (e instanceof SocketTimeoutException) {
                            // 重新提交验证   在这里最好限制提交次数
                            Log.e("need_reconnect", e.getMessage());
                        }

                        if (e instanceof ConnectTimeoutException) {
                            Log.e("frost_connection", e.getMessage());
                        }
                        Log.e("login", e.toString());
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(getApplicationContext(), "网络连接超时，请检查网络后重试", Toast.LENGTH_SHORT).show();
                            }
                        });
                    }

                    @Override
                    public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                        String information = response.body().string();
                        Log.i(TAG, information);
                        JSONObject json = null;
                        try {
                            json = new JSONObject(information);
                            String code = json.getString("code");
                            switch (code) {
                                case "200":
                                    Log.i(TAG, "登陆成功");
                                    runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            Toast.makeText(getApplicationContext(), "登陆成功", Toast.LENGTH_SHORT).show();
                                        }
                                    });
                                    JSONObject dataJson = json.getJSONObject("data");
                                    String token = dataJson.getString("token");
                                    Log.i(TAG, "token:  " + token);
                                    Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                                    //intent.putExtra("personInformation", new PersonInformation(username, token));
                                    intent.putExtra("token", token);
                                    startActivity(intent);
                                    break;
                                case "400":
                                    Log.i(TAG, "登陆失败，信息缺失");
                                    AlertDialog.Builder builder2 = new AlertDialog.Builder(LoginActivity.this);
                                    builder2.setTitle("登陆失败");
                                    builder2.setMessage("登陆信息缺失");
                                    builder2.setPositiveButton("好的", null);
                                    runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            builder2.show();
                                        }
                                    });
                                    break;
                                case "401":
                                    Log.i(TAG, "登陆失败，用户名或密码不对");
                                    AlertDialog.Builder builder3 = new AlertDialog.Builder(LoginActivity.this);
                                    builder3.setTitle("登陆失败");
                                    builder3.setMessage("请检查用户名或密码是否正确");
                                    builder3.setPositiveButton("好的", null);
                                    //builder3.show();
                                    //Toast.makeText(getApplicationContext(), "登陆失败,请检查用户名或密码是否正确", Toast.LENGTH_SHORT).show();
                                    runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            builder3.show();
                                        }
                                    });
                                    break;
                            }
                        } catch (JSONException e) {
                            Log.e(TAG, "JSON解析失败");
                            e.printStackTrace();
                        }

                    }
                };
                NetAPI.postJson("api/login/", body, callback);
            }
        });
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                this.finish();
                return true;
        }
        return super.onOptionsItemSelected(item);
    }
}